<template>
  <PublicLoading v-if="loading.mounted" />
  <div v-else class="dt-main-tabs-content">
    <!--dt-content-left可选-->
    <!-- <div class="dt-content-left">
      <PmComChatList />
    </div> -->
    <div class="dt-content-main">
      <div class="dt-content-head">
        <div class="dt-content-head-tab">
          <div class="dt-head-title">
            <div class="dt-head-breadcrumb" @click="goBack">
              <i class="el-icon-arrow-left"></i>
              <span>返回</span>
              <em>|</em>
            </div>
            <span>添加创客订单</span>
          </div>
        </div>
      </div>
      <div class="dt-content-page">
        <el-form :model="orderRuleForm" ref="orderRuleForm" label-width="118px" label-position="left" class="dt-outOrder-box">
          <el-form-item label="管理单位" prop="manageCompanyId" :rules="{ required: true, message: '请选择管理单位！', trigger: 'blur'}">
            <el-select v-model="orderRuleForm.manageCompanyId" placeholder="请选择管理单位" style="width:540px" @change="manageCompany">
              <el-option v-for="item in orderRuleForm.manageCompanyList" :key="item.id" :label="item.projectName" :value="item.id+''">
              </el-option>
            </el-select>
            <el-button type="text" class="dt-output-total" @click="goSkip">添加管理单位</el-button>
          </el-form-item>
          <el-form-item label="所属专业" prop="majorId" :rules="{ required: true, message: '请选择所属专业！', trigger: 'blur'}">
            <el-select v-model="orderRuleForm.majorId" placeholder="请选择所属专业" style="width:540px" :disabled="orderRuleForm.majorList.length==0"
              @change="electMajor">
              <el-option v-for="item in orderRuleForm.majorList" :key="item.id" :label="item.projectName" :value="item.id+''">
              </el-option>
            </el-select>
            <el-button type="text" class="dt-output-total" @click="goSkip">添加专业</el-button>
          </el-form-item>
          <el-form-item label="规划产值" prop="projectOutput" :rules="{ required: true, message: '请输入规划产值！', trigger: 'blur'}">
            <el-input placeholder="请输入规划产值" v-model.trim="orderRuleForm.projectOutput" style="width:540px" disabled class="dt-je-box por"
              @blur="saveFormData">
              <template slot="append">元</template>
              <div v-if="orderRuleForm.projectOutput!=0" slot="append" class="dt-je-China poa">
                {{$tools.moneyLower(orderRuleForm.projectOutput)}}
              </div>
            </el-input>

            <span v-if="orderRuleForm.isShowOutput" class="dt-ml-6">剩余可分配产值 {{$tools.moneyLower(orderRuleForm.residueOutput)}} 元</span>
          </el-form-item>
          <div class="dt-add-order">
            <el-form-item prop="projectName" label="项目节点" :rules="{ required: true, message: '请选择项目名称！', trigger: 'blur'}">
              <el-select placeholder="请选择" style="width:580px; margin-right:4px;" v-model="orderRuleForm.projectName" disabled @blur="saveFormData">
              </el-select>
            </el-form-item>
            <el-form-item prop="nodeId" label-width="4px">
              <el-select v-model="orderRuleForm.nodeId" placeholder="请选择" style="width:540px" disabled
                :rules="{ required: true, message: '请选择项目节点！', trigger: 'blur'}" @change="saveFormData">
                <el-option v-for="item in nodeList" :key="item.id" :label="item.nodeName" :value="item.id+''">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <el-form-item label="创客订单数量" prop="region">
            <el-input-number v-model="orderRuleForm.num" @change="handleChange" :min="1" :max="99" label="描述文字"
              @blur="saveFormData"></el-input-number>
          </el-form-item>
          <div class="dt-add-order" v-for="(taskJson,index) in orderRuleForm.taskJson" :key="taskJson.key">
            <el-form-item :label="'创客订单'+(index+1)" :prop="'taskJson.' + index + '.taskName'"
              :rules="[{ required: true, message: '请输入订单名称', trigger: 'blur'},{ min: 5, max: 40, message: '请输入5-40字订单名称', trigger: 'blur' },{ validator: validateTaskName, trigger: 'blur' }]">
              <el-input v-model.trim="taskJson.taskName" placeholder="请输入订单名称" show-word-limit maxlength="40" style="width:580px;margin-right:4px;"
                @blur="saveFormData"></el-input>
            </el-form-item>
            <el-form-item :prop="'taskJson.' + index + '.output'" label-width="4px"
              :rules="[{ required: true, message: '请输入项目产值', trigger: 'blur' },{ validator: validateNumber, trigger: 'blur' }]">
              <el-input placeholder="请输入项目产值" v-model.trim="taskJson.output" style="width:540px; margin-right:114px;" class="dt-je-box por"
                @input="getTotalPrice(index)" @blur="saveFormData">
                <template slot="append">元</template>
                <div slot="append" class="dt-je-China poa" v-if="taskJson.output!=0">{{$tools.moneyLower(taskJson.output)}}</div>
              </el-input>
            </el-form-item>
          </div>

          <el-form-item v-if="orderRuleForm.totalPrice!=0">
            <p class="dt-output-total ml588">合计产值：{{$tools.moneyLower(orderRuleForm.totalPrice)}} 元 <span
                v-if="orderRuleForm.totalPrice>orderRuleForm.initResidueOutput">剩余产值不足，请调整产值后重新提交</span></p>
          </el-form-item>

          <el-form-item>
            <el-button class="dt-button" type="primary" @click="submitFormOutOrder('orderRuleForm')" :loading="loading.createOrder">提交</el-button>
            <el-button class="dt-button" @click="resetFormOutOrder('orderRuleForm')">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

  </div>
</template>
<script>
export default {
  data() {
    return {
      uid: this.$tools.getDecrypt(this.$store.state.uid), //用户id
      secret_uid: this.$store.state.uid, //加密用户id
      loading: { mounted: false, createOrder: false },
      nodeList: [],
      orderRuleForm: {
        num: 4,
        manageCompanyList: [],
        manageCompanyId: '',
        majorList: [],
        majorId: '',
        projectOutput: 0,
        residueOutput: 0,
        isShowOutput: false,
        initResidueOutput: 0,
        projectName: '',
        nodeId: '',
        taskJson: [
          { taskName: '', output: '', key: 1 },
          { taskName: '', output: '', key: 2 },
          { taskName: '', output: '', key: 3 },
          { taskName: '', output: '', key: 4 }
        ],
        totalPrice: 0
      }
    }
  },
  computed: {
    query() {
      return this.$tools.getQuery(this)
    }
  },
  methods: {
    showCard() {
      this.dataCard.isShowCard = true
    },
    goSkip() {
      if (this.query.isDetail) {
        this.$router.push('/main/#/pm?tab=detail&elTab=1&rootProjectId=' + this.query.rootProjectId)
      } else {
        this.$router.push('/main/#/pm?tab=create&elTab=1&rootProjectId=' + this.query.rootProjectId)
      }
    },
    goBack() {
      if (this.query.isDetail) {
        this.$router.push('/main/#/pm?tab=detail&elTab=2&rootProjectId=' + this.query.rootProjectId)
      } else {
        this.$router.push('/main/#/pm?tab=create&elTab=2&rootProjectId=' + this.query.rootProjectId)
      }
    },
    // 订单名称唯一性验证
    titleOnlyCheck(demandTitle, callback) {
      // type类型1企业、2创客
      var data = [{ user_id: this.uid, demand_title: encodeURIComponent(demandTitle), demand_id: '' }],
        domain = [this.$store.state.HOST],
        path = ['/Walk/demand_title_only_check'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              callback()
            } else {
              callback(new Error(data.message))
            }
          })
        })
        .catch((error) => {})
    },
    checkDuplicate(array, propertyName, value) {
      var seen = {}
      for (var i = 0; i < array.length; i++) {
        var currentValue = array[i][propertyName]
        if (seen[currentValue] && currentValue == value) {
          return true // 发现重复值
        } else {
          seen[currentValue] = true
        }
      }
      return false // 没有发现重复值
    },
    validateTaskName(rule, value, callback) {
      if (value) {
        if (this.checkDuplicate(this.orderRuleForm.taskJson, 'taskName', value)) {
          callback(new Error('订单名称重复'))
        } else {
          this.titleOnlyCheck(value, callback)
        }
      } else {
        callback()
      }
    },
    validateNumber(rule, value, callback) {
      if (value <= 0) {
        callback(new Error('请输入大于 0 的产值'))
      } else {
        callback()
      }
    },
    handleChange(number) {
      let taskJsonLength = this.orderRuleForm.taskJson.length
      if (number > this.orderRuleForm.taskJson.length) {
        for (let i = 0; i < number - taskJsonLength; i++) {
          this.orderRuleForm.taskJson.push({ taskName: '', output: '', key: Date.now() + '_' + Math.random() })
        }
      } else {
        // this.orderRuleForm.taskJson.splice(number - 1, 1)
        this.orderRuleForm.taskJson.splice(number, this.orderRuleForm.taskJson.length)
      }
    },
    getManageCompanyList() {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.query.rootProjectId
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/manageUnitSelector'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.orderRuleForm.manageCompanyList = data.data
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    manageCompany(value) {
      // console.log(value, 6789)
      this.orderRuleForm.majorId = ''
      this.orderRuleForm.projectOutput = 0
      this.orderRuleForm.isShowOutput = false
      this.getMajorList(value)
    },
    getMajorList(id) {
      var data = [{ userId: this.uid, manageUnitId: id }],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/majorSelector'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.orderRuleForm.majorList = data.data
              this.saveFormData()
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    electMajor(value) {
      let manageCompanyId = this.orderRuleForm.manageCompanyId
      this.orderRuleForm.isShowOutput = true
      this.ouputShow(manageCompanyId, value)
    },
    ouputShow(MasterUid, majorId) {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.query.rootProjectId,
            majorMasterUid: MasterUid,
            majorId: majorId
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/project/ouputShow'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.orderRuleForm.projectOutput = data.data.planOutput
              this.orderRuleForm.residueOutput = data.data.residueOutput
              this.orderRuleForm.initResidueOutput = data.data.residueOutput
              this.saveFormData()
            } else {
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    createOrder() {
      var data = [
          {
            userId: this.uid,
            projectId: this.query.rootProjectId,
            manageCompanyId: this.orderRuleForm.manageCompanyId,
            majorId: this.orderRuleForm.majorId,
            nodeId: this.query.nodeId,
            taskJson: JSON.stringify(this.orderRuleForm.taskJson)
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/task/addCKTask'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success',
                onClose: () => {
                  if (this.query.isDetail) {
                    localStorage.removeItem('orderRuleFormCk')
                    this.$router.push(
                      '/main/#/pm?tab=detail&elTab=2&rootProjectId=' + this.query.rootProjectId + '&nodeId=' + this.orderRuleForm.nodeId
                    )
                  } else {
                    this.$router.push(
                      '/main/#/pm?tab=create&elTab=2&rootProjectId=' + this.query.rootProjectId + '&nodeId=' + this.orderRuleForm.nodeId
                    )
                  }
                  this.loading.createOrder = false
                  //关闭创建标签
                  this.$tools.setTabs(this, this.secret_uid, 'close', { hashName: 'pm-add-ck' })
                }
              })
            } else if (data.code === 430) {
              this.loading.createOrder = false
              this.$confirm('此操作需认证发票, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                cancelButtonClass: 'dt-button-cancle is-plain',
                type: 'warning'
              })
                .then(() => {
                  window.open('/myInvoice')
                })
                .catch(() => {
                  // this.$message({
                  //   type: 'info',
                  //   message: '已取消删除'
                  // })
                })
            } else {
              this.loading.createOrder = false
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    submitFormOutOrder(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.orderRuleForm.totalPrice > this.orderRuleForm.initResidueOutput) {
            this.$message({
              message: '剩余产值不足，请调整产值后重新提交!',
              type: 'warning',
              duration: 3500
            })
          } else {
            this.loading.createOrder = true
            this.createOrder()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetFormOutOrder(formName) {
      this.$refs[formName].resetFields()
      this.createPmRuleForm = {
        projectName: '',
        output: '',
        planDays: '',
        dateArr: '',
        projectMaster: '',
        description: '',
        workContent: ''
      }
      this.goBack()
    },
    getTreeData(data) {
      var items = [],
        deepEach = function (data) {
          var item = {}
          for (var key in data) {
            if (key !== 'children') {
              item[key] = data[key]
            } else {
              if (data['children'].length) {
                deepEach(data['children'][0])
              }
            }
          }
          items.push(item)
        }
      if (data) {
        deepEach(data)
      }
      return items.reverse()
    },
    getNodeList() {
      var data = [
          {
            userId: this.uid,
            rootProjectId: this.query.rootProjectId
          }
        ],
        domain = [this.$store.state.DOMAIN],
        path = ['/project/node/projectNodeList'],
        dataAxios = this.$tools.getDataAxios(this, domain, path, data)
      Promise.all(dataAxios)
        .then((response) => {
          this.$tools.callbackAxios(this, response, (response) => {
            var data = response[0].data
            if (data.code === 200) {
              this.nodeList = this.getTreeData(data.data.firstNode)
            } else {
              this.nodeList = []
              this.$message({
                message: data.message,
                type: 'warning',
                onClose: () => {}
              })
            }
          })
        })
        .catch((error) => {})
    },
    getTotalPrice(index) {
      if (this.orderRuleForm.taskJson[index].output.indexOf('.') < 0) {
        this.orderRuleForm.taskJson[index].output = this.orderRuleForm.taskJson[index].output.split('.')[0].substring(0, 9)
      } else if (this.orderRuleForm.taskJson[index].output.split('.')[0].length > 9) {
        this.orderRuleForm.taskJson[index].output =
          this.orderRuleForm.taskJson[index].output.split('.')[0].substring(0, 9) +
          (this.orderRuleForm.taskJson[index].output.split('.')[1] ? '.' + this.orderRuleForm.taskJson[index].output.split('.')[1] : '')
      }
      //输入金额过滤
      let that = this
      let regStrs = [
        ['^0(\\d+)$', '$1'],
        ['[^\\d\\.]+$', ''],
        ['\\.(\\d?)\\.+', '.$1'],
        ['^(\\d+\\.\\d{2}).+', '$1']
      ]
      for (let i = 0; i < regStrs.length; i++) {
        let reg = new RegExp(regStrs[i][0])
        that.orderRuleForm.taskJson[index].output = that.orderRuleForm.taskJson[index].output.replace(reg, regStrs[i][1])
      }
      // 获取总金额
      this.orderRuleForm.totalPrice = 0
      this.orderRuleForm.taskJson.forEach((item) => {
        this.orderRuleForm.totalPrice = this.$tools.accAdd(this.orderRuleForm.totalPrice, item.output)
      })
      //计算剩余产值
      this.orderRuleForm.residueOutput = this.orderRuleForm.initResidueOutput
      this.orderRuleForm.residueOutput = this.$tools.Subtr(this.orderRuleForm.residueOutput, this.orderRuleForm.totalPrice)
    },
    saveFormData() {
      localStorage.removeItem('orderRuleFormCk')
      // 在这里保存表单数据，可以使用 localStorage 或者其他方式
      localStorage.setItem('orderRuleFormCk', JSON.stringify(this.orderRuleForm))
    }
  },
  mounted() {
    if (this.query.rootProjectId) {
      this.getManageCompanyList()
      this.orderRuleForm.projectName = this.query.projectName
      this.getNodeList()
      this.orderRuleForm.nodeId = this.query.nodeId
    }
    if (localStorage.getItem('orderRuleFormCk')) {
      this.orderRuleForm = JSON.parse(localStorage.getItem('orderRuleFormCk'))
      this.orderRuleForm.residueOutput = this.orderRuleForm.initResidueOutput
      this.orderRuleForm.residueOutput = this.$tools.Subtr(this.orderRuleForm.residueOutput, this.orderRuleForm.totalPrice)
      console.log(this.orderRuleForm, 789)
    }
  },
  watchQuery: true
}
</script>
<style scoped>
.dt-ml-6 {
  margin-left: 6px;
}
.dt-outOrder-box {
  padding: 30px;
  width: 1248px;
}
.dt-outOrder-box >>> .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::after {
  content: '*';
  color: #f56c6c;
  margin-left: 4px;
}
.dt-outOrder-box >>> .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
  content: '';
  color: #f56c6c;
  margin-right: 0px;
}
.dt-output-total {
  text-align: left;
  line-height: 18px;
}
.ml588 {
  margin-left: 588px;
}
.dt-output-total span {
  margin-left: 26px;
  color: #f5222d;
}
.dt-add-order {
  display: flex;
  display: -webkit-flex;
  flex-direction: row;
}

.dt-je-China {
  top: 10px;
  right: 64px;
  color: #909399;
}
.dt-button {
  margin-top: 12px;
  padding: 10px 27px;
}
.el-button + .el-button {
  margin-left: 6px;
}
</style>